<template>
  <BasicModal title="分解" width="600" v-bind="$attrs"
    :canFullscreen="false"
    :centered="true"
    :destroyOnClose="true"
    @register="registerModal"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" :model="decomposeModel" />
  </BasicModal>
</template>

<script lang="ts" name="BankRunningModal" setup>
import {ref, computed, unref, reactive} from 'vue';
import {BasicModal, useModalInner} from '/@/components/Modal';
import {BasicForm, useForm} from '/@/components/Form/index';
import {bankDecomposeSave, bankRunningById, bankDecomposeCheck} from "/@/views/full/bank/types/bank.api";
import {useMessage} from "/@/hooks/web/useMessage";

import moment from 'dayjs'

const $message = useMessage();
// 表单modal
const decomposeModel = reactive<any>({})
// 声明Emits
const emit = defineEmits(['success', 'register']);

// 表单配置
const [registerForm, {resetFields, setFieldsValue, validate}] = useForm({
  schemas: [
    { label: "parentId", field: "parentId", component: "Input", show: false },
    { label: "id", field: "id", component: "Input", show: false },
    { label: "vl", field: "vl", component: "Input", show: false },
    { label: "类型", field: "sflx", component: "Input", show: false },
    {
      label: "收支账户",
      field: "bankId",
      component: "JDictSelectTag",
      componentProps: {
        dictCode: "chee_bank,djm,id@ddlxBank",
        placeholder: " ",
        allowClear: true,
        showSearch: true,
        stringToNumber: true,
        dropdownMatchSelectWidth: false,
        getPopupContainer: () => document.body,
      },
      required: true
    },
    {
      label: "金额",
      field: "je",
      component: "InputNumber",
      componentProps: { 
        placeholder: "",
      },
      //dynamicRules: ({ model, schema }) => decomposeValidate(model, schema),
      dynamicRules: ({ model }) => {
        return [
          { required: true, message: '金额不能为空！' },
          { validator: (_, value) => {
              return new Promise((resolve, reject) => {
                if (!value) {
                  return resolve();
                }
                if (!(/^-?[1-9]+(\.\d+)?$|^-?0(\.\d+)?$|^-?[1-9]+[0-9]*(\.\d+)?$/g.test(value))) {
                  return reject('输入的金额必须为数字，可以有小数！');
                }
                // 后台校验
                let params = {
                  parentId:  model.parentId,
                  sflx: model.sflx,
                  id: model.id,
                  je: model.je,
                  vl: model.vl,
                }
                bankDecomposeCheck(params).then((res) => {
                  res.success ? resolve() : reject(res.message || '校验失败');
                })
                .catch((err) => {
                  reject(err.message || '验证失败');
                });
              });
            },
          },
        ]
      },
    },
    {
      label: "部门",
      field: "ddlx",
      component: "JDictSelectTag",
      componentProps: {
        dictCode: "ddlxType",
        placeholder: " ",
        stringToNumber: true,
        getPopupContainer: () => document.body,
      },
    },
    { label: "备注", field: "bz", component: "InputTextArea", componentProps: { placeholder: " " } }
  ],
  labelWidth: 120,
  baseColProps: {span: 20},
  showActionButtonGroup: false,
});

const isUpdate = ref(true);
//表单赋值
const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
  setModalProps({confirmLoading: false});
  isUpdate.value = !!data?.isUpdate;
  await resetFields()
  let record = data?.record || {}
  if (isUpdate.value) {
    record = await bankRunningById({parentId: data.model.id, id:data?.record?.id});
  }
  record.parentId = data.model.id;
  record.sflx = data.model.sflx;
  record.vl = data.model.zje;
  record.bankId = data.model.bankId;
  record.bz = data.model.djm + data.model.zje + "元分解"
  await setFieldsValue(record)
  console.info(data.model);
});

//表单提交事件
async function handleSubmit() {
  try {
    setModalProps({confirmLoading: true});
    const values = await validate();
    await bankDecomposeSave(values).then((res) => {
      if (res.success) {
        $message.createMessage.success(res.message);
        //关闭弹窗
        closeModal();
        emit("success")
      } else {
        $message.createMessage.warning(res.message);
      }
    });
  } catch (e) {
    console.log("handleSubmit - 提交校验出错", e);
  } finally {
    setModalProps({confirmLoading: false});
  }
}

/**
 * 分解金额校验
 */
async function decomposeValidate(parentId, id) {
  try {
    let params = {
      parentId,
      id
    };
    const res = await bankDecomposeCheck(params);
    if (res.success) {
      return Promise.resolve();
    } else {
      return Promise.reject(res.message || '校验失败');
    }
  } catch (e) {
    return Promise.reject('校验失败,可能是断网等问题导致的校验失败');
  }
}

</script>

<style lang="less" scoped>

</style>
